<%@ page import="com.example.util.DBUtil" %>
<%@ page import="com.example.domain.User" %>
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>查看购物车</title>
</head>
<body>
    <h1>购物车内容</h1>
    
    <%
        // 检查用户是否已登录
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
    %>
        <p>用户未登录</p>
        <a href="../auth/login.jsp">前往登录</a>
    <%
        } else {
    %>
        <p>当前用户ID: <%= currentUser.getId() %></p>
        <p>当前用户名: <%= currentUser.getUsername() %></p>
        
        <h2>购物车中的商品</h2>
        <%
            Connection conn = null;
            try {
                conn = DBUtil.getConnection();
                
                String cartSql = "SELECT c.id, c.sale_num, c.sale_price, c.sale_money, p.product_name " +
                                "FROM tb_cart c " +
                                "JOIN tb_product p ON c.product_id = p.id " +
                                "WHERE c.member_id = ?";
                PreparedStatement cartStmt = conn.prepareStatement(cartSql);
                cartStmt.setInt(1, currentUser.getId());
                ResultSet cartRs = cartStmt.executeQuery();
                
                if (!cartRs.next()) {
        %>
                    <p>购物车为空</p>
        <%
                } else {
        %>
                    <table border="1">
                        <tr>
                            <th>购物车ID</th>
                            <th>商品名称</th>
                            <th>数量</th>
                            <th>单价</th>
                            <th>小计</th>
                        </tr>
        <%
                    do {
        %>
                        <tr>
                            <td><%= cartRs.getInt("id") %></td>
                            <td><%= cartRs.getString("product_name") %></td>
                            <td><%= cartRs.getInt("sale_num") %></td>
                            <td><%= cartRs.getDouble("sale_price") %></td>
                            <td><%= cartRs.getDouble("sale_money") %></td>
                        </tr>
        <%
                    } while (cartRs.next());
        %>
                    </table>
        <%
                }
            } catch (Exception e) {
        %>
                <p style="color: red;">错误: <%= e.getMessage() %></p>
        <%
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (Exception e) {
                        // 忽略关闭连接的异常
                    }
                }
            }
        %>
    <%
        }
    %>
    
    <br>
    <a href="debug_cart.jsp">返回调试页面</a>
</body>
</html>